import re
from django.contrib.auth.backends import ModelBackend
from .models import User


def jwt_respones_ph(token, user=None, request=None):
    return {
        'user_id': user.id,
        'username': user.username,
        'token': token,
    }


class UsernameModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断username是用户名还是手机号
        # try:
        #     # 是用户名
        #     user = User.objects.get(mobile=username)
        # except:
        #     try:
        #         # 是手机号
        #         user = User.objects.get(username=username)
        #     except:
        #         return None
        # if not user.check_password(password):
        #     return user
        # else:
        #     return None
        if re.match(r'^1[3-9]\d{9}]$', username):
            user = User.objects.filter(mobile=username).first()
        else:
            user = User.objects.filter(username=username).first()
        if user.check_password(password):
            return user
        else:
            return None